package com.ledim.chat;

public class ByteArrayReader {

    private byte[] mBuf;
    private int pos;

    public ByteArrayReader(byte[] buf) {
        this.mBuf = buf;
    }

    /**
     * 读取32位整数
     *
     * @return
     */
    public int readUint32() {
        if (mBuf.length < pos + 4) {
            return 0;
        }
        int value = mBuf[pos++] & 0x000000FF;
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        return value;
    }

    /**
     * 读取32位整数，偏移offset
     *
     * @param offset
     * @return
     */
    public int readUint32(int offset) {
        if (mBuf.length < offset + 4) {
            return 0;
        }
        int value = mBuf[pos++] & 0x000000FF;
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        return value;
    }

    /**
     * 读取16位整数
     *
     * @return
     */
    public int readUint16() {
        if (mBuf.length < pos + 2) {
            return 0;
        }
        int value = mBuf[pos++] & 0x000000FF;
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        return value;
    }

    /**
     * 读取16位整数
     *
     * @return
     */
    public int readUint16(int offset) {
        if (mBuf.length < offset + 2) {
            return 0;
        }
        int value = mBuf[pos++] & 0x000000FF;
        value = ((value << 8) | (mBuf[pos++] & 0x000000FF));
        return value;
    }

    /**
     * 读取8位整数
     *
     * @return
     */
    public int readUinit8() {
        if (mBuf.length < pos + 1) {
            return 0;
        }
        int value = mBuf[pos++] & 0x000000FF;
        return value;
    }

    /**
     * 读取8位整数
     *
     * @return
     */
    public int readUinit8(int offset) {
        if (mBuf.length < offset + 1) {
            return 0;
        }
        int value = mBuf[pos++] & 0x000000FF;
        return value;
    }

    /**
     * 读取字符串
     *
     * @param len
     * @return
     */
    public String readString(int len) {
        if (mBuf.length < pos + len) {
            return null;
        }
        byte[] values = new byte[len];
        System.arraycopy(mBuf, pos, values, 0, len);
        return new String(values);
    }

    /**
     * 读取字符串
     *
     * @param len
     * @return
     */
    public String readString(int offset, int len) {
        if (mBuf.length < offset + len) {
            return null;
        }
        byte[] values = new byte[len];
        System.arraycopy(mBuf, offset, values, 0, len);
        return new String(values);
    }
}